package oop.controller.action.user;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;

import oop.data.User;
import oop.db.dao.UserDAO;

public class SignUpAction extends UserManagerAction {

	@Override
	public void performImpl() throws Exception {
		title("Đăng kí làm thành viên của website trắc nghiệm :: Powered by CSForce");
		if (isUserLoggedIn()){
			setNextAction("homepage");		
			return;
		}
		if ("Sign Up".equals(request.getParameter("signUp"))) {
			int error = 0;
			if (isUserExist()) {
				// nguoi dung da ton tai
				request.setAttribute("userExist", "true");
				error++;
			}
			if (isEmailExist()) {
				// email da duoc dung
				request.setAttribute("emailUnavailable", "true");
				error++;
			}
			if (isValidUserName() == false) {
				// Ten nguoi dung nhap sai qui cach
				request.setAttribute("invalidUserName", "true");
				error++;
			}
			if (isValidEmail() == false) {
				// Email sai qui cach
				request.setAttribute("invalidEmail", "true");
				error++;
			}
			if (isValidPassword() == false) {
				// Password sai qui cach
				request.setAttribute("invalidPass", "true");
				error++;
			}

			if (error > 0) {
				request.setAttribute("error", "true");
			} else {
				User user = null;
				user = UserDAO.create(request.getParameter("userName"), request
						.getParameter("fullName"), request
						.getParameter("password"), request
						.getParameter("userEmail"));

				if (user != null) {
					request.getSession().setAttribute("user", user);
					request.getSession().setAttribute("login", true);
					setNextAction("homepage");
				} else {
					request.setAttribute("sqlError", "true");
				}
			}
		}
	}

	private boolean isValidUserName() throws ServletException, IOException {
		String userName = request.getParameter("userName");
		String userExp = "[a-zA-Z][a-zA-Z0-9]+";
		if ((userName.matches(userExp)) && (isEmpty(userName) == false))
			return true;
		else
			return false;
	}

	private boolean isValidPassword() throws ServletException, IOException {
		String pass = request.getParameter("password");
		String confPass = request.getParameter("confirmPass");
		if ((pass.compareTo(confPass) != 0) || (isEmpty(pass)))
			return false;
		return true;
	}

}
